﻿using System;
using log4net.Config;
using TimeMachine.Engine;
using TimeMachine.Engine.Agents;

namespace MetricsAgent
{
	internal class Program
	{
		private readonly ProjectSettingsFileStore store;

		private Program(string dataPath)
		{
			store = new ProjectSettingsFileStore(dataPath, new ProjectSettingsSerializer());
		}

		private static void Main(string[] args)
		{
			XmlConfigurator.Configure();
			string dataPath = args.Length > 0 ? args[0] : ".";
			string projectName = args.Length > 1 ? args[1] : null;
			var program = new Program(dataPath);
			if (projectName == null)
				program.ActualizeAllProjects();
			else
				program.Actualize(projectName);
		}

		private void Actualize(string projectName)
		{
			IProjectSettings projectSettings = store.Get(projectName);
			try
			{
				new MeasurementsAgent(projectSettings).Run();
				new ReportsAgent(projectSettings).Run();
			}
			catch (Exception e)
			{
				Console.WriteLine(projectSettings.VcsRepo.Url);
				Console.WriteLine(e.ToString());
			}
		}

		private void ActualizeAllProjects()
		{
			Array.ForEach(store.GetProjectNames(), Actualize);
		}
	}
}